package com.ctrip.ec.api.admin.controller.goods;
import com.ctrip.ec.api.admin.common.ValidateException;
import com.ctrip.ec.api.admin.model.goods.GoodsModel;
import com.ctrip.ec.api.admin.model.query.QueryModel;
import com.ctrip.ec.biz.dao.goods.*;
import com.ctrip.ec.biz.dao.store.StoreDao;
import com.ctrip.ec.biz.dao.user.UserDao;
import com.ctrip.ec.biz.entity.goods.*;
import com.ctrip.ec.biz.entity.role.SysRole;
import com.ctrip.ec.biz.entity.store.StoreEntity;
import com.ctrip.ec.dal.PagerSetting;
import com.ctrip.ec.api.admin.common.RequestContext;
import com.google.common.base.Strings;
import jdk.nashorn.internal.ir.RuntimeNode;
import org.bouncycastle.cert.ocsp.Req;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/goods")
public class GoodsController{
    @Autowired
    private GoodsDao goods;

    @Autowired
    private GoodsRebateDao goodsRebate;

    @Autowired
    private GoodsImageDao goodsImage;

    @Autowired
    private GoodsCategoryDao goodsCategory;

    @Autowired
    private UserDao user;

    @Autowired
    private StoreDao store;



    @Autowired
    private GoodsSpecDao goodsSpec;

    @Value("${imageDomain}")
    private  String imageDomain;

    @PostMapping("list")
    public List<GoodsEntityEx> list(@RequestBody QueryModel model) throws  SQLException{
        PagerSetting setting = model.build();
        setting.setOrderBy("cat_sort desc,cat_id desc,id desc");

        Long storeId = RequestContext.getStoreId();
        List<Long> roleIds = user.roleIds(RequestContext.getUserId());

        setting.appendWhere("agent_id=" + RequestContext.getAgentId());
        if(roleIds.contains(SysRole.superadmin.getId()) == false){
            setting.appendWhere("store_id=" + storeId);
        }
        List<GoodsEntityEx> list = goods.listEx(setting);
        List<Long> storeIds = list.stream().map(t->t.getStoreId()).collect(Collectors.toList());
        List<Long> goodsIds = list.stream().map(t->t.getId()).collect(Collectors.toList());
        List<StoreEntity> storeList= store.listByIds(storeIds);
        List<GoodsSpecEntity> specList = goodsSpec.sumStoreCount(goodsIds);

        for(GoodsEntityEx entity : list){
            Optional<StoreEntity> storeEntity = storeList.stream().filter(t->t.getId().equals(entity.getStoreId())).findFirst();
            if(storeEntity.isPresent()){
                entity.setStoreName(storeEntity.get().getName());
            }

            Optional<GoodsSpecEntity> specEntity = specList.stream().filter(t->t.getGoodsId().equals(entity.getId())).findFirst();
            if(specEntity.isPresent()){
                entity.setStoreCount(specEntity.get().getStoreCount());
            }
        }

        RequestContext.setResponseHeaderCount(setting.getRecordCount());
        return list;
    }



    @GetMapping("detail/{id}")
    public GoodsModel detail(@PathVariable Long id) throws SQLException {
        GoodsModel model = new GoodsModel();
        GoodsEntity entity = goods.entity(id);
        model.setGoods(entity);
        model.setImageList(goodsImage.listByGoodsId(id));

        for(GoodsImageEntity imageEntity : model.getImageList()){
            imageEntity.setImageUrl(imageEntity.getImageUrl());
        }

        model.setRebateList(goodsRebate.listByGoodsId(id));
        model.setSpecList(goodsSpec.listByGoodsId(id));
        return model;
    }

    @PostMapping("save")
    public  Long save(@RequestBody GoodsModel model) throws SQLException {

        if(model.getSpecList()== null || model.getSpecList().size()==0){
            throw new ValidateException("请添加商品规格");
        }
        for(GoodsSpecEntity goodsSpecEntity : model.getSpecList()){
            if(goodsSpecEntity.getStoreCount() == null){
                throw new ValidateException("库存不能为空");
            }
        }

        GoodsEntity entity = model.getGoods();
        entity.setAgentId(RequestContext.getAgentId());

        Timestamp now = new Timestamp(System.currentTimeMillis());
        if(entity.add()){
            entity.setCreateTime(now);
            entity.setIsDelete(false);
            entity.setUserId(RequestContext.getUserId());
            entity.setStoreId(RequestContext.getStoreId());
            entity.setCreateTime(new Timestamp(System.currentTimeMillis()));
        }
        entity.setUpdateTime(new Timestamp(System.currentTimeMillis()));

        GoodsCategoryEntity goodsCategoryEntity = goodsCategory.entity(entity.getCatId());
        if(goodsCategoryEntity != null){
            entity.setCatSort(goodsCategoryEntity.getSortNum());
        }

        entity.setUpdateTime(now);

        goods.save(entity);
        BigDecimal max= new BigDecimal(0);
        BigDecimal min = new BigDecimal(Integer.MAX_VALUE);
        BigDecimal total = new BigDecimal(0);
        int count =0;
        if(model.getSpecList()!= null && model.getSpecList().size()>0){
            for(GoodsSpecEntity specEntity :model.getSpecList()){

                specEntity.setGoodsId(entity.getId());
                goodsSpec.save(specEntity);
                count++;
                max = max.max(specEntity.getShopPrice());
                min = min.min(specEntity.getShopPrice());
                total.add(specEntity.getShopPrice());

            }
            entity.setMaxPrice(max);
            entity.setMinPrice(min);
            entity.setAvgPrice(total.divide(new BigDecimal(count),2, RoundingMode.HALF_UP));
            goods.save(entity);
        }
        if(model.getImageList()!= null && model.getImageList().size()>0){
            //先删除不用的图片
            List<GoodsImageEntity> oldList = goodsImage.listByGoodsId(entity.getId());
            List<Long> newImageIds = model.getImageList().stream().filter(t->t.getId()!=null && t.getId()!=0).map(t->t.getImageId()).collect(Collectors.toList());

            for(GoodsImageEntity goodsImageEntity: oldList){
                if(!newImageIds.contains(goodsImageEntity.getImageId())){//没有就删除
                    goodsImage.delete(goodsImageEntity.getId());
                }
            }
            //老的里面没有的就是需要添加的
            List<Long> oldImageIds = oldList.stream().map(t->t.getImageId()).collect(Collectors.toList());
            for(GoodsImageEntity imageEntity: model.getImageList()){
                if(!oldImageIds.contains(imageEntity.getImageId())) {
                    imageEntity.setGoodsId(entity.getId());
                    goodsImage.save(imageEntity);
                }
            }
        }

        if(model.getRebateList()!= null && model.getImageList().size()>0){
            for (GoodsRebateEntity rebateEntity:model.getRebateList()){
                rebateEntity.setGoodsId(entity.getId());
                goodsRebate.save(rebateEntity);
            }
        }

        return entity.getId();
    }

    @PostMapping("update")
    public  void update(@RequestBody GoodsModel model) throws  SQLException{
        goods.save(model.getGoods());
    }

    @PostMapping("delete")
    public  void delete(@RequestBody List<Long> ids) throws SQLException {
        goods.delete(ids);
    }

    @PostMapping("erase")
    public void erase(@RequestBody List<Long> ids) throws  SQLException{
        goods.erase(ids);
    }

    @PostMapping("unerase")
    public  void unerase(@RequestBody List<Long> ids) throws  SQLException{
        goods.unerase(ids);
    }
}
